const Base = require('./base.js');
const paymentStatus = require('../constants/paymentStatus');
const businessType = require('../constants/businessType');
module.exports = class extends Base {
  __before() {
    super.__before();
    this.informationService = think.rpc.information.information;
    this.commentsService = think.rpc.information.comments;
    this.paymentService = think.rpc.payment.payment;
    this.userService = think.rpc.user.user;
    this.categoryService = think.rpc.information.category;
  }
  async findAction() {
    const id = this.intVal('id', 0);
    if (id) {
      const data = await this.informationService.queryById(id);
      if (!think.isEmpty(data)) {
        const user = await this.userService.queryById(data.user_id, 'avatar,nickname');
        if (!think.isEmpty(data)) {
          think.extend(data, user);
        }
      }
      data.createTime = think.timeUtil.beforeTimeFormat(data.create_time);
      return this.success(think.camelResult(data));
    }
    return this.fail('id can not be empty!');
  }
  // 浏览
  async viewAction() {
    const id = this.intVal('id');
    await this.informationService.incViewCount(id);
    return this.success();
  }
  validData() {
    const telephone = this.strVal('telephone');
    const content = this.strVal('content');
    const categoryId = this.intVal('categoryId');
    const address = this.strVal('address');
    const longitude = this.doubleVal('longitude');
    const latitude = this.doubleVal('latitude');
    if (!content) {
      think.throw('请输入要发布的内容');
    }
    if (!telephone) {
      think.throw('请输入您的手机号码');
    }
    if (!categoryId) {
      think.throw('请选择发布的类目');
    }
    if (!address || !longitude || !latitude) {
      think.throw('请选择发布的地址');
    }
  }
  /**
   * 发布信息内容
   */
  async createAction() {
    this.validData();
    const telephone = this.strVal('telephone');
    const content = this.strVal('content');
    const categoryId = this.intVal('categoryId');
    const address = this.strVal('address');
    const longitude = this.doubleVal('longitude');
    const latitude = this.doubleVal('latitude');
    const userId = this.getUserId();
    let imgSrcs = this.post('imgSrcs');
    if (think.isEmpty(imgSrcs)) {
      imgSrcs = '';
    } else {
      imgSrcs = imgSrcs.join(',');
    }
    const paymentId = this.intVal('paymentId');
    // 分布式的事务，后期需要补偿
    const amount = await this.categoryService.queryFee(categoryId);
    // 修改
    if (paymentId > 0) {
      // 删除旧数据
      const paymentInfo = await this.paymentService.queryById(paymentId, 'business_id,business_type,status');
      if (!think.isEmpty(paymentInfo) && paymentInfo.status === paymentStatus.notpayed && businessType.infomation === paymentInfo.business_type) {
        if (await this.informationService.queryUserIdById(paymentInfo.business_id) !== userId) {
          return this.fail('非法数据');
        }
        await this.informationService.removeById(paymentInfo.business_id);
        await this.paymentService.removeById(paymentId);
      }
    }
    const newInformationId = await this.informationService.create({
      telephone,
      userId,
      imgSrcs,
      content,
      totalAmount: amount,
      status: amount <= 0 ? 1 : 0,
      isPayed: amount <= 0 ? 1 : 0,
      topAmount: 0,
      categoryId,
      address,
      lng: longitude,
      lat: latitude
    });
    try {
      if (amount > 0) { // 需要支付;
        const notifyUrl = this.ctx.origin.replace('http:', 'https:') + '/bst/payment/wxnotify';
        think.logger.info('notifyUrl', notifyUrl);
        const rt = await this.paymentService.create({
          businessId: newInformationId,
          amount,
          ip: think.isIPv4(this.ctx.ip) ? this.ctx.ip : '127.0.0.1',
          openid: this.getUser().openid,
          userId,
          notifyUrl
        });
        return this.success(rt);
      }
      // 不需要支付
      return this.success();
    } catch (e) {
      await this.paymentService.removePayment(newInformationId);
      throw e;
    }
  }
  async upAction() {
    const id = this.intVal('id');
    if (id) {
      await this.informationService.upCount(id);
      return this.success();
    } else {
      return this.fail('id can not be empty');
    }
  }
  // 获取分类信息
  async dataAction() {
    const orderType = this.intVal('orderType', 0);
    let lastId = this.intVal('lastId', 0);
    const lat = this.doubleVal('lat', 0);
    const lng = this.doubleVal('lng', 0);
    const page = this.intVal('page', 1);
    const pageSize = think.PAGE_SIZE;
    const data = await this.informationService.queryOnlineData({
      page: page,
      pageSize,
      lastId,
      categoryId: this.intVal('cid', 0),
      keywords: this.strVal('k', ''),
      lng,
      lat,
      orderType
    });
    if (lastId === 0) {
      lastId = await this.informationService.queryMaxId({
        categoryId: this.intVal('cid', 0),
        keywords: this.strVal('k', '')
      });
    }
    const rt = [];
    if (data.length > 0) {
      const userIds = [];
      const informationIds = [];
      data.forEach(element => {
        informationIds.push(element.id);
        if (userIds.indexOf(element.user_id) === -1) {
          userIds.push(element.user_id);
        }
        rt.push({
          id: element.id,
          userId: element.user_id,
          categoryName: element.category_name,
          categoryId: element.category_id,
          content: element.content,
          time: think.timeUtil.beforeTimeFormat(element.create_time),
          address: element.address,
          avatar: element.avatar,
          imgSrcs: element.img_srcs,
          commentCount: element.comment_count,
          telephone: element.telephone,
          upCount: element.up_count,
          viewedCount: element.viewed_count
        });
      });
      if (informationIds.length > 0) {
        const commentRows = await this.commentsService.queryByInformationIdRange(informationIds);
        if (commentRows && commentRows.length) { // 合并
          const userIds = [];
          commentRows.forEach(commentRow => {
            if (commentRow.user_id && userIds.indexOf(commentRow.user_id) === -1) {
              userIds.push(commentRow.user_id);
            }
            if (commentRow.to_user_id && userIds.indexOf(commentRow.to_user_id) === -1) {
              userIds.push(commentRow.to_user_id);
            }
          });
          // 查询评论的人员信息
          const userRows = await this.userService.queryByUserIds(userIds, 'id,nickname,avatar');
          const userId = this.getUserId(0);
          rt.forEach(dataItem => {
            dataItem.comments = commentRows.filter(el => el.information_id === dataItem.id).map(el => {
              const user = think.oneOrDefault(userRows, u => u.id === el.user_id, {});
              el.nickname = user.nickname || '';
              el.avatar = user.avatar || '';
              const toUser = think.oneOrDefault(userRows, u => u.id === el.to_user_id, {});
              return {
                nickname: el.nickname,
                userId: el.user_id,
                isMine: el.user_id === userId,
                toNickname: toUser.nickname || '',
                avatar: el.avatar,
                content: el.content,
                id: el.id
              };
            });
          });
        }
      }
      if (userIds.length) {
        const userRows = await this.userService.queryByUserIds(userIds, 'id,nickname,avatar');
        userRows.forEach(el => {
          rt.filter(i => i.userId === el.id).forEach(i => {
            i.nickname = el.nickname;
            i.avatar = el.avatar;
          });
        });
      }
    }
    return this.success({data: rt, lastId, hasNoMore: rt.length < pageSize});
  }
  async myDataAction() {
    const userId = this.getUserId();
    const data = await this.informationService.queryOnlineData({
      page: this.intVal('page', 1),
      pageSize: think.PAGE_SIZE,
      userId,
      categoryId: this.intVal('cid', 0),
      keywords: this.strVal('k', '')
    });
    return this.success(data);
  }

  async removeAction() {
    const id = parseInt(this.post('id'));
    if (id) {
      await this.informationService.removeById(this.getUserId(), id);
      return this.success();
    }
    return this.fail('删除失败');
  }
};
